package com.tencent.bk.sdk.iam.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.tencent.bk.sdk.iam.config.IamConfiguration;
import com.tencent.bk.sdk.iam.dto.response.ResponseDTO;
import com.tencent.bk.sdk.iam.dto.system.TokenDTO;
import com.tencent.bk.sdk.iam.service.HttpClientService;
import com.tencent.bk.sdk.iam.service.TokenService;
import com.tencent.bk.sdk.iam.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TokenServiceImpl implements TokenService {
    private static final Logger log = LoggerFactory.getLogger(TokenServiceImpl.class);
    private final IamConfiguration iamConfiguration;
    private final HttpClientService httpClientService;
    private String token = null;

    public TokenServiceImpl(IamConfiguration iamConfiguration, HttpClientService httpClientService) {
        this.iamConfiguration = iamConfiguration;
        this.httpClientService = httpClientService;
    }

    private void initToken() {
        try {
            String getTokenResponse = this.httpClientService.doHttpGet(String.format("/api/v1/model/systems/%s/token", this.iamConfiguration.getSystemId()));
            if (StringUtils.isNotBlank(getTokenResponse)) {
                log.debug("Get token response|{}", getTokenResponse);
                ResponseDTO<TokenDTO> tokenResponse = (ResponseDTO) JsonUtil.fromJson(getTokenResponse, new TypeReference<ResponseDTO<TokenDTO>>() {
                });
                if (tokenResponse != null) {
                    log.debug("Get token from iam|{}|{}|{}", new Object[]{tokenResponse.getCode(), tokenResponse.getMessage(), ((TokenDTO)tokenResponse.getData()).getToken()});
                    if (tokenResponse.getCode() == 0L) {
                        this.token = ((TokenDTO)tokenResponse.getData()).getToken();
                    }
                }
            }

            if (this.token == null) {
                throw new RuntimeException("Get token failed!");
            }
        } catch (Exception var3) {
            log.error("Get iam system token failed!", var3);
            throw new RuntimeException(var3);
        }
    }

    public String getToken() {
        if (this.token == null) {
            this.initToken();
        }

        return this.token;
    }
}
